import React, { useState } from 'react'
import { Button, Form, Input, Text, Textarea, View, switchTab } from 'remax/one'
import { cloud, showToast, showLoading, hideLoading } from 'remax/wechat'
import { ImageUpload, Space } from 'annar'
import { mutateCloud, requestCloud } from '@/hooks/use-cloud'
import styles from './index.css'

export default () => {
  const [files, setFiles] = useState<string[]>([])

  const submit = async (values: any) => {
    let { name, description, price, originalPrice, quota } = values
    name = name.trim()
    description = description.trim()
    price = Math.round(parseFloat(price) * 100) / 100
    originalPrice = Math.round(parseFloat(originalPrice) * 100) / 100
    quota = parseInt(quota)

    if (!files.length) {
      showToast({ title: '未上传图片', icon: 'none' })
      return
    }
    if (!name || !description || !price || !originalPrice || !quota) {
      showToast({ title: '所有内容均应正确填写', icon: 'none' })
      return
    }
    if (price < 0.01) {
      showToast({ title: '活动价最低1分', icon: 'none' })
      return
    }
    if (price > originalPrice) {
      showToast({ title: '活动价不能高于原价', icon: 'none' })
      return
    }
    if (quota < 5 || quota > 999) {
      showToast({ title: '每日限额应是5-999人', icon: 'none' })
      return
    }

    try {
      showLoading({ title: '上传中', mask: true })
      const ts = Date.now()
      const res = await Promise.all(
        files.map((v, i) => {
          const match = v.match(/\.[^\.]+$/)
          const suffix = match ? match[0].toLowerCase() : ''
          return cloud.uploadFile({
            cloudPath: `promotion/${ts}-${i}${suffix}`,
            filePath: v,
          })
        })
      )
      hideLoading()

      let imgUrls = res.map(v => v.fileID)
      const { fileList } = await cloud.getTempFileURL({ fileList: imgUrls })
      imgUrls = fileList.map((v: any) => v.tempFileURL)
      await requestCloud('add-promotion', {
        name,
        description,
        imgUrls,
        price,
        originalPrice,
        quota,
      })
      mutateCloud('list-promotion')
      switchTab({ url: `/pages/promotion-list/index` })
    } catch ({ errMsg }) {
      showToast({ title: '网络错误', icon: 'none' })
    }
  }

  return (
    <>
      <Space className={styles.imgUploadArea} direction="vertical" size={20}>
        <View>
          <Text className={styles.labelText}>请上传活动图片：</Text>
          <Text className={styles.tipText}>*最多可上传3张</Text>
        </View>
        <ImageUpload
          files={files}
          multiple
          multipleCount={3 - files.length}
          maxCount={3}
          sizeType={['compressed']}
          onChange={(files: any) => {
            setFiles(files)
          }}
        />
      </Space>
      <View className={styles.inputArea}>
        <Form
          onSubmit={({ target: { value } }) => {
            submit(value)
          }}
        >
          <Space className={styles.inputBox} direction="vertical" size={20}>
            <Text className={styles.labelText}>商品名称：</Text>
            <Input
              className={styles.input}
              name="name"
              maxLength={20}
              placeholder="20字以内"
            />
            <View>
              <Text className={styles.labelText}>原价：</Text>
              <Text className={styles.tipText}>
                *请填写您店里真实价格以免被投诉
              </Text>
            </View>
            <Input
              className={styles.input}
              name="originalPrice"
              type="digit"
              placeholder=""
            />
            <View>
              <Text className={styles.labelText}>活动价：</Text>
              <Text className={styles.tipText}>
                *包含引流费用10%，不满5元按5元计
              </Text>
            </View>
            <Input
              className={styles.input}
              name="price"
              type="digit"
              placeholder="不能高于原价"
            />
            <View>
              <Text className={styles.labelText}>每日限额：</Text>
              <Text className={styles.tipText}>
                *每天最多允许多少人购买本商品
              </Text>
            </View>
            <Input
              className={styles.input}
              name="quota"
              type="number"
              maxLength={3}
              placeholder="最少5人，最多999人"
            />
            <Text className={styles.labelText}>说明：</Text>
            <Textarea
              className={styles.textarea}
              name="description"
              maxLength={100}
              placeholder="100字以内"
            />
            <Button className={styles.submitBtn} type="submit">
              提交审核
            </Button>
          </Space>
        </Form>
      </View>
    </>
  )
}
